package com.androidproject.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONObject;

import com.androidproject.Constantes;
import com.androidproject.Header;
import com.androidproject.Item;
import com.androidproject.R;
import com.androidproject.LineArrayAdapter;
import com.androidproject.modele.Programme;
import com.androidproject.modele.ProgrammeParJour;
import com.androidproject.modele.ProgrammeTV;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class ProgrammeTvActivity extends ListActivity/*Activity*/ {

	private Intent intentAccueil;
	private Intent intentClassement;
	private Intent intentCalendrier;
	private Intent intentProgrammeTV;
	private Intent intentFacebook;
	private Intent intentTwitter;
	
	private ProgrammeTV programmeTv;
	private ProgressDialog progressD;
	
	private List<Item> items;
	
	public class TaskObject extends AsyncTask<String, Void, StringBuffer> {

		private HttpResponse response;
		private JSONObject jSonObject;
		
		@Override
		//String... pour sp�cifier qu'il n'y a pas de nombre de param�tre sp�cifique, il faut juste que ce soit le m�me type
		protected StringBuffer doInBackground(String... url) {
			
			StringBuffer chaine = new StringBuffer("");
			
			try{
				
				AndroidHttpClient client = AndroidHttpClient.newInstance("user-agent"); 
				URI uri = new URI(url[0]);
				HttpGet request = new HttpGet(); 
				request.setURI(uri); 
				response = client.execute(request); 
				client.close();
				
				// Get the response 
				InputStream inputStream = response.getEntity().getContent(); 
				BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); 
				String line = "";
				
				while ((line = rd.readLine()) != null) { 
					chaine.append(line);
				} 
				
			} catch(Exception e){ 
				chaine.append(e.getMessage());
				
			} finally { } 
			
			return chaine;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			progressD = ProgressDialog.show(ProgrammeTvActivity.this, Constantes.WAIT_TITLE,Constantes.WAIT_MESSAGE_PROGRAMME_TV, true);
		}
		
		@Override
		protected void onPostExecute(StringBuffer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			progressD.dismiss();
			
			try{ //Traitement du JSON 
				
				jSonObject = new JSONObject(result.toString());
				JSONObject resultatTV = jSonObject.getJSONObject(Constantes.PROGRAMME_TV);
				
				//Création du programme tv
				programmeTv = new ProgrammeTV();
				
				//Récupération des enfants
				for(int index = 0; index < resultatTV.length(); index++){
					JSONArray d0 = new JSONArray(resultatTV.getString("D"+index));
					ProgrammeParJour programmePJ = new ProgrammeParJour(d0.getJSONObject(0).getString(Constantes.PROGRAMME_DAY));
					
					for(int i = 0; i< d0.length(); i++){ 
						Programme programme = new Programme(d0.getJSONObject(i).getString(Constantes.PROGRAMME_HOUR), 
															d0.getJSONObject(i).getString(Constantes.PROGRAMME_LOGO_NAME), 
															d0.getJSONObject(i).getString(Constantes.PROGRAMME_CHANNEL), 
															d0.getJSONObject(i).getString(Constantes.PROGRAMME_GAME));
						programmePJ.getProgrammes().add(programme);
					}
					programmeTv.getListJours().add(programmePJ);
				}
				
				items = new ArrayList<Item>();
				
				for (ProgrammeParJour programmePJ : programmeTv.getListJours()) {
					
					 items.add(new Header(programmePJ.getDate()));
						
					for (Programme programme : programmePJ.getProgrammes()) {
						items.add(new Programme(programme.getHour(), programme.getLogoname(), programme.getChannel(), programme.getGame()));
					}
				}
				
		        LineArrayAdapter adapter = new LineArrayAdapter(ProgrammeTvActivity.this, items);
		        setListAdapter(adapter);
		        
		        
//				//Récupération de D0
//				
//				JSONArray d0 = new JSONArray(resultatTV.getString("D0"));
//				ProgrammeParJour programmePJ = new ProgrammeParJour(d0.getJSONObject(0).getString(Constantes.PROGRAMME_DAY));
//				
//				for(int i = 0; i< d0.length(); i++){ 
//					Programme programme = new Programme(d0.getJSONObject(i).getString(Constantes.PROGRAMME_HOUR), 
//														d0.getJSONObject(i).getString(Constantes.PROGRAMME_LOGO_NAME), 
//														d0.getJSONObject(i).getString(Constantes.PROGRAMME_CHANNEL), 
//														d0.getJSONObject(i).getString(Constantes.PROGRAMME_GAME));
//					programmePJ.getProgrammes().add(programme);
//				}
//				programmeTv.getListJours().add(programmePJ);
////				
//				ListView listView = (ListView) findViewById(R.id.ListViewJourneesTV);
//				listView.setAdapter(new LineAdapterProgrammeTV(ProgrammeTvActivity.this, programmeTv.getListJours()));
				
			} catch(Exception e){ 
				Log.e("Erreur",e.getMessage()); 
			} finally { } 
			
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_programme_tv);
		
		TaskObject task = new TaskObject(); 
		task.execute(new String[] {Constantes.FLUX_PROGRAMME_MATCH});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(0, 1, 0, "News").setIcon(R.drawable.logo_journal);
		menu.add(0, 2, 0, "Classement").setIcon(R.drawable.logo_classement);
		menu.add(0, 3, 0, "Programme TV").setIcon(R.drawable.logo_tv);
		menu.add(0, 4, 0, "Calendrier").setIcon(R.drawable.logo_calendrier);
		menu.add(0, 5, 0, "Facebook").setIcon(R.drawable.logo_facebook);
		menu.add(0, 6, 0, "Twitter").setIcon(R.drawable.logo_twitter);
	    
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		case 1:
			intentAccueil = new Intent(this, MainActivity.class);
			startActivity(intentAccueil);
			return true;
		
		case 2:
			intentClassement = new Intent(this, ClassementActivity.class);
			startActivity(intentClassement);
			return true;
		
		case 3:
			intentProgrammeTV = new Intent(this, ProgrammeTvActivity.class);
			startActivity(intentProgrammeTV);
			return true;
		
		case 4:
			intentCalendrier = new Intent(this, CalendrierActivity.class);
			startActivity(intentCalendrier);
			return true;
	
		case 5:
			intentFacebook = new Intent(this, FacebookActivity.class);
			startActivity(intentFacebook);
			return true;
		
		case 6:
			intentTwitter = new Intent(this, TwitterActivity.class);
			startActivity(intentTwitter);
			return true;
		
		default:
			return true;
		}
	}
	
}
